<template>
  <div class="left-main" ref="scrollContainer">
    <NotData v-show="notData" />
    <div v-show="!notData" class="preview-container" ref="preview"></div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, onUnmounted, nextTick, watch } from 'vue'
// import bus from '@/utils/eventBus'
import { renderAsync } from 'docx-preview'
import fileManagement from '@/stores/fileManagement'
import loading from '@/stores/loading'
import { endsWithChinese, removeSpaces, startsWithNumberOrDecimal } from '@/utils/tool'
import { customAttr } from '@/utils/const'
import { ElMessage } from 'element-plus'
import mammoth from 'mammoth'

const props = defineProps({
  documentContent: {
    type: ArrayBuffer,
    required: false,
  },
})

const emit = defineEmits(['getTitle'])
const fileManagementStore = fileManagement()
const loadingStore = loading()
const scrollContainer = ref(null)
const preview = ref(null)
const notData = ref(true)

function previewFile(file: any) {
  notData.value = true
  fileManagementStore.updatedFileAnalysisStatus(false)
  const options = {
    className: 'docx',
    debug: false,
    renderFooters: false,
    renderFootnotes: false,
    breakPages: true,
    ignoreLastRenderedPageBreak: false,
    // inWrapper: true,
    // ignoreWidth: false, //禁用页面的渲染宽度
    // ignoreHeight: false, //禁用页面的渲染高度
    // ignoreFonts: true,
    // breakPages: true, // 启用分页
    // ignoreLastRenderedPageBreak: false,
    // experimental: false,
    // trimXmlDeclaration: true,
    // useBase64URL: false,
    // renderChanges: false,
    // renderHeaders: true, //启用标头渲染
    // renderFooters: true, //启用footers渲染
    // renderFootnotes: true,
    // renderEndnotes: true,
    // renderComments: false,
  }
  const container: any = preview.value
  previewScrollTo()
  renderAsync(file, container, undefined, options)
    .then(async (res) => {
      console.log('Word文档渲染完成')
      await nextTick()
      notData.value = false
      fileManagementStore.updatedFileAnalysisStatus(true)
      configTitle(file)
      const section = container.querySelectorAll('.docx-wrapper section') || []
      for (let i = 0; i < section.length; i++) {
        const s = section[i]
        if (removeSpaces(s.innerText)) {
          continue
        }
        s.classList.add('no-text')
      }
    })
    .catch((error: any) => {
      console.error('渲染失败', error)
      ElMessage({
        type: 'error',
        message: '渲染失败，如果是.doc文件，请使用软件转为.docx格式',
        duration: 3000,
      })
    })
}

// 提取标题
async function configTitle(file: any) {
  const reader: any = new FileReader()
  reader.readAsArrayBuffer(file)
  reader.onload = async () => {
    const result = await mammoth.convertToHtml({ arrayBuffer: reader.result })
    const html = result.value
    const tempDiv = document.createElement('div')
    tempDiv.innerHTML = html
    const children = Array.from(tempDiv.children)
    let titleDiv = document.createElement('div')
    children.forEach((child) => {
      if (!['H1', 'H2', 'H3', 'H4', 'H5', 'H6'].includes(child.tagName)) {
        tempDiv.removeChild(child)
      } else if(!child.innerText) {
        tempDiv.removeChild(child)
      } else {
        titleDiv.innerHTML+=`<p class="item">${child.innerText}</p>`
      }
    })
    emit('getTitle', {
    html: titleDiv.innerHTML,
    el: titleDiv,
  })
    // document.body.innerHTML = ''
    // document.body.appendChild(tempDiv)

    // 提取所有标题元素（h1 - h6）
    // const headings = []
    // for (let i = 1; i <= 6; i++) {
    //   const title:any = tempDiv.getElementsByTagName(`h${i}`)
    //   for (let j = 0; j < title.length; j++) {
    //     headings.push(title[j].innerText)
    //   }
    // }
    // 输出提取的标题
    // console.log(headings, '===')
  }
  reader.onerror = (e) => {
    console.log(e, 'reader.error')
  }

  return
  const docxBox: any = preview.value
  const pList = docxBox!.querySelectorAll('p[class^="docx_"]')
  const div = document.createElement('div')
  const articleList = []
  for (let i = 0; i < pList.length; i++) {
    const p = pList[i]
    if (p.innerHTML.includes('<span id="_') && !!p.innerText) {
      p.setAttribute(customAttr.dataIndex, i + 1)
      if (p.parentNode) {
        articleList.push(p.parentNode)
      }
      div.innerHTML += `<p class="item" ${customAttr.dataIndex}="${i + 1}">${p.innerText}<i></i></p>`
    }
  }
  fileManagementStore.updatedArticleList(articleList)
  emit('getTitle', {
    html: div.innerHTML,
    el: div,
  })
}

function previewScrollTo(num: number = 0) {
  scrollContainer &&
    scrollContainer.value &&
    scrollContainer.value.scrollTo({
      top: num,
      behavior: 'smooth',
    })
}
watch(
  () => props.documentContent,
  (file: File) => {
    if (!file) return
    previewFile(file)
  },
)
</script>

<style scoped lang="scss">
.left-main {
  background-color: #fff;
  // overflow-y: auto; /* 当内容超出高度时显示垂直滚动条 */
  // // overflow-x: hidden;

  :deep(.docx-wrapper) {
    background-color: #fff; /* 将 #yourColor 替换为你想要的颜色 */
    section {
      // padding-left: 40pt !important;
      // padding-right: 40pt !important;
      article {
        width: 100%;
        table {
          max-width: 100% !important;
        }
      }
      &.no-text {
        display: none;
      }
    }
    img {
      max-width: 80%;
    }
  }
}

mark {
  background-color: yellow; /* 高亮颜色 */
  padding: 0; /* 根据需要调整 */
}
/* 添加一个类名，例如 'docx-container' */
</style>
